package cn.com.edu.nju.ecrec.cluster;

import java.sql.*;
import java.util.List;

import cn.com.edu.nju.ecrec.dao.*;
import cn.com.edu.nju.ecrec.model.*;
import cn.com.edu.nju.ecrec.util.DaoName;

public class RelationUpdate {
	Connection con;
	Statement statement;
	
	public void relation(){
		UserCluster uc = new UserCluster(5);
		int[][] userCluster = uc.KModes();
		UserInfoDao ud = DaoFactory.getInstance().getDao(DaoName.USER_INFO_DAO);
		List<UserInfo> uis = ud.getAll();
		ItemCluster ic = new ItemCluster(5);
		int[][] itemCluster = ic.KModes();
		ItemDao id = DaoFactory.getInstance().getDao(DaoName.ITEM_DAO);
		List<Item> is = id.getAll();
		
		this.DBUtil();
		
		try {
			for(int i = 0;i < userCluster.length; i ++){
				for(int j = 0;j < userCluster[0].length;j ++){
					if(userCluster[i][j]==1){
						String sql = "insert into userCluster (infoID,clusterID) values (" + uis.get(i).getInfoID() + "," + j + ")";
						statement.execute(sql);
					}
				}
			}
			
			for(int i = 0;i < itemCluster.length; i ++){
				for(int j = 0;j < itemCluster[0].length;j ++){
					if(itemCluster[i][j]==1){
						String sql = "insert into itemCluster (pid,clusterID) values (" + is.get(i).getPid() + "," + j + ")";
						statement.execute(sql);
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		this.closeDB();
	}
	
	private void DBUtil(){
		try {
			String driverName = "com.mysql.jdbc.Driver";
			String userName = "root";
			String userPasswd = "123456";
			String url = "jdbc:mysql://localhost:3307/ECRec";
			Class.forName(driverName).newInstance();
			con = DriverManager.getConnection(url, userName, userPasswd);
			statement = con.createStatement();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void closeDB(){
		try {
			statement.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		RelationUpdate ru = new RelationUpdate();
		ru.relation();
	}
}
